package com.bstek.urule.console.servlet.parameter;

import com.bstek.urule.RuleException;
import com.bstek.urule.console.EnvironmentUtils;
import com.bstek.urule.console.FreemarkerUtils;
import com.bstek.urule.console.User;
import com.bstek.urule.console.XmlUtils;
import com.bstek.urule.console.repository.Repository;
import com.bstek.urule.console.repository.RepositoryService;
import com.bstek.urule.console.repository.model.FileType;
import com.bstek.urule.console.repository.model.RepositoryFile;
import com.bstek.urule.console.servlet.RequestContext;
import com.bstek.urule.console.servlet.base.BaseController;
import com.bstek.urule.model.library.variable.Variable;
import com.bstek.urule.model.library.variable.VariableCategory;
import com.bstek.urule.parse.deserializer.VariableLibraryDeserializer;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author zhouchaoliang
 * @since 2021/12/9
 */
@Controller
public class ParameterController extends BaseController {

    private static final String CLASSIFY_COOKIE_NAME="_lib_classify";

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private VariableLibraryDeserializer variableLibraryDeserializer;

    @GetMapping("/urule/parametereditor")
    public ModelAndView paremeter(HttpServletRequest req, HttpServletResponse resp) {
        ModelAndView mv = new ModelAndView("/parameter-editor");
        mv.addObject("contextPath", req.getContextPath());
        return mv;
    }

    @ResponseBody
    @PostMapping(value = "/urule/parameter/saveFile")
    public void saveFile(@RequestBody ParameterSaveDto parameterSaveDto, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=parameterSaveDto.getFile();
        List<Variable> data = parameterSaveDto.getData();
        String versionComment=parameterSaveDto.getVersionComment();
        Boolean newVersion = parameterSaveDto.getNewVersion();

        User user= EnvironmentUtils.getLoginUser(new RequestContext(req, resp));
        try{
            String content = new FreemarkerUtils("parameter.xml").data("data",data).build();
            System.out.println(content);
            repositoryService.saveFile(file,content,newVersion,versionComment,user);
        }catch(Exception ex){
            throw new RuleException(ex);
        }
    }

    /**
     * 获取指定项目下的所有变量的类
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping(value = "/urule/api/parameter/variables")
    public List<Object> variables(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String projectName = req.getParameter("projectName");
        User user = EnvironmentUtils.getLoginUser(new RequestContext(req, resp));
        boolean classify = getClassify(req, resp);
        FileType[] types = new FileType[]{FileType.VariableLibrary};
        Repository repo = repositoryService.loadRepository(projectName, user, classify, types, null);

        //过滤出项目里所有的vl文件
        List<RepositoryFile> children = repo.getRootFile().getChildren().get(0).getChildren().get(0).getChildren().get(0).getChildren();
        List<RepositoryFile> result = children.stream().filter(i -> i.getName().endsWith(FileType.VariableLibrary.toString())).collect(Collectors.toList());

        List<Object> results = new ArrayList<>();
        //取出所有vl文件里的实体
        for (RepositoryFile file : result) {
            InputStream inputStream = repositoryService.readFile("/" + projectName + "/" + file.getName(), null);
            Element element = XmlUtils.parseXml(inputStream);

            List<VariableCategory> deserialize = variableLibraryDeserializer.deserialize(element);
            if (!CollectionUtils.isEmpty(deserialize)) {
                deserialize.forEach(i -> results.add(i));
            }
        }
        return results;
//        writeObjectToJson(resp, results);
    }

    /**
     * 设置cookie
     * @param req
     * @param resp
     * @return
     */
    private boolean getClassify(HttpServletRequest req,HttpServletResponse resp) {
        String classifyValue=req.getParameter("classify");
        if(StringUtils.isBlank(classifyValue)){
            Cookie[] cookies=req.getCookies();
            if(cookies!=null){
                for(Cookie cookie:cookies){
                    if(CLASSIFY_COOKIE_NAME.equals(cookie.getName())){
                        classifyValue=cookie.getValue();
                        break;
                    }
                }
            }
        }else{
            Cookie classifyCookie=new Cookie(CLASSIFY_COOKIE_NAME,classifyValue);
            classifyCookie.setMaxAge(2100000000);
            resp.addCookie(classifyCookie);
        }
        boolean classify=true;
        if(StringUtils.isNotBlank(classifyValue)){
            classify=Boolean.valueOf(classifyValue);
        }
        return classify;
    }
}
